package com.zhhtech.zhh.utils

import android.app.Activity
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.pm.ResolveInfo
import android.net.Uri
import androidx.lifecycle.LifecycleOwner
import com.alibaba.fastjson.JSONObject
import com.zhhtech.zhh.ui.base.BaseActivity
import com.zhhtech.zhh.ui.dialog.showAlertDialog
import com.zhhtech.zhh.ui.ext.DefaultLifecycleObserver
import com.zhhtech.zhh.ui.ext.toastMessageLong
import com.zhhtech.zhh.ui.helper.ILoa
import com.zhhtech.zhh.ui.helper.localSendBroadcast
import com.zhhtech.zhh.ui.utils.Logger
import com.xuexiang.xupdate.XUpdate
import com.xuexiang.xupdate._XUpdate
import com.xuexiang.xupdate.service.OnFileDownloadListener
import com.xuexiang.xupdate.utils.UpdateUtils
import java.io.File
import kotlin.math.roundToInt


/**
 * 启动App
 */
fun startApp(context: Context?, menuConfig: JSONObject) {
    val appName = menuConfig["appName"]?.toString() ?: ""
    menuConfig["packageName"]?.toString()?.let { packageName ->
        val intent = context?.packageManager?.getLaunchIntentForPackage(packageName)
        if (intent != null) {
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        } else {
//            val intentFilter = IntentFilter().apply {
//                addAction(Intent.ACTION_PACKAGE_ADDED)
//                addDataScheme("package")
//            }
//            context.registerReceiver(,intentFilter)
            val iLoa: ILoa? = context as? ILoa
            (context as? BaseActivity<*>)?.showAlertDialog {
                message(message = "该功能需要下载${appName}APP，是否下载?")
                negativeButton { }
                positiveButton(name = "下载") {
                    iLoa?.installApk(menuConfig)
                }
            }
        }
    }
//    val intent = context.packageManager.getLaunchIntentForPackage(packageName)
//    if (intent != null) {
//        context.startActivity(intent)
//    } else {
//        "未找到相关App，请先安装！".toastMessageLong()
//    }
}

fun getMimeType(typeName: String?): String {
    var mimeType = "/"
    if (typeName == null){
        return mimeType
    }
    when (typeName.substringAfterLast(".", "")) {
        "pdf" -> mimeType = "application/pdf"
        "jpg" -> mimeType = "image/jpeg"
        "png" -> mimeType = "image/png"
        "doc", "docx" -> mimeType = "application/msword"
        "xls", "xlsx" -> mimeType = "application/vnd.ms-excel"
        "ppt", "pptx" -> mimeType = "application/vnd.ms-powerpoint"
        else -> {}
    }
    return mimeType
}

fun ILoa.installApk(menuConfig: JSONObject) {
    val context = mLoaContext ?: return
    val packageName = menuConfig["packageName"]?.toString() ?: return
    val appName = menuConfig["appName"]?.toString() ?: ""
    val intent = context.packageManager?.getLaunchIntentForPackage(packageName)
    if (intent != null) {
        localSendBroadcast(context, Intent.ACTION_PACKAGE_ADDED)
        return
    }
    menuConfig["url"]?.toString()?.let { url ->
        val mUpdateManager = XUpdate.newBuild(context)
            .apkCacheDir(UpdateUtils.getDefaultDiskCacheDirPath())
            .build()
        mLoaLifecycleOwner?.lifecycle?.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                mUpdateManager.cancelDownload()
            }
        })
        mUpdateManager.download(url, object : OnFileDownloadListener {

            private var sHorizontalProgressDialog: ProgressDialog? = null

            override fun onStart() {
                Logger.e("onStart")
                sHorizontalProgressDialog = ProgressDialog(context).apply {
                    setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                    setCancelable(false)
                    max = 100
                    setMessage("${appName}下载进度")
                }
                sHorizontalProgressDialog?.show()
            }

            override fun onProgress(progress: Float, total: Long) {
                sHorizontalProgressDialog?.apply {
                    setProgress((progress * 100).roundToInt())
                    if (getProgress() >= max) {
                        dismiss()
                        sHorizontalProgressDialog = null
                    }
                }
            }

            override fun onCompleted(file: File): Boolean {
                sHorizontalProgressDialog?.apply {
                    dismiss()
                    sHorizontalProgressDialog = null
                }
                _XUpdate.startInstallApk(context, file)
                return false
            }

            override fun onError(throwable: Throwable) {
                Logger.e(throwable)
                sHorizontalProgressDialog?.apply {
                    dismiss()
                    sHorizontalProgressDialog = null
                }
            }
        })
    }
}

/**
 * 判断是否安装App
 */
fun isInstalledApp(context: Activity, packageName: String) = context.packageManager.getLaunchIntentForPackage(packageName) != null


fun Context.openSystemEmail() {
    val uri = Uri.parse("mailto:3802**92@qq.com")
    val packageInfos: List<ResolveInfo> = packageManager.queryIntentActivities(Intent(Intent.ACTION_SENDTO, uri), 0)
    val packageList: MutableList<String> = ArrayList()
    val emailIntents: MutableList<Intent> = ArrayList()
    for (i in packageInfos.indices) {
        val packageName = packageInfos[i].activityInfo.packageName
        if (packageList.contains(packageName)) {
            packageList.remove(packageName)
        }
        packageList.add(packageName)
    }
    for (i in packageList.indices) {
        packageManager.getLaunchIntentForPackage(packageList[i])?.let { emailIntents.add(it) }
    }
    var chooserIntent: Intent? = null
    if (emailIntents.isNotEmpty()) {
        chooserIntent = Intent.createChooser(emailIntents.removeAt(0), "选择邮箱打开方式!")
    }
    if (chooserIntent != null) {
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailIntents.toTypedArray())
        startActivity(chooserIntent)
    } else {
        "未找到可用邮箱！".toastMessageLong()
    }
}